package main

import "fmt"

func main() {
	timeSeries := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
	duration := 1
	fmt.Println(findPoisonedDuration(timeSeries, duration))
}

//#link: https://leetcode-cn.com/problems/teemo-attacking/
func findPoisonedDuration(timeSeries []int, duration int) int {
	sum := 0
	// 中毒开始,结束时间
	beginTime := timeSeries[0]
	endTime := beginTime + duration - 1

	// 当 i 小于时间序列时
	for i := 1; i < len(timeSeries); i++ {
		// 中毒还未结束
		if timeSeries[i] <= endTime {
			if targetTime := timeSeries[i] - beginTime; targetTime > 0 {
				sum += targetTime
			}
			beginTime = timeSeries[i]
		} else {
			if endTime-beginTime >= 0 {
				sum += endTime - beginTime + 1
			}
			beginTime = timeSeries[i]
		}
		endTime = beginTime + duration - 1
	}
	if endTime-beginTime >= 0 {
		sum += endTime - beginTime + 1
	}
	return sum
}
